<!-- eslint-disable max-len -->
<template>
  <a-form-model
    ref="formComp"
    :model="formData"
    :rules="rules"
    layout="horizontal"
    style="padding: 20px 25px 10px 40px"
    class="AsteriskAfter editTestFormBox h100 newEditStyle rightDrawerWithoutCol "
  >
    <!-- 表单填写的基本信息 -->
    <fieldset>
      <legend>任务配置</legend>
      <a-row :gutter="40">
        <!-- 车型代码 -->
        <a-col :md="6" :sm="24">
          <a-form-model-item :label="$t('modelCode')" prop="modelId">
            <car-model-select
              mode="default"
              :query="{ time }"
              :has-all="false"
              :default-value="formData.modelId"
              :clear="true"
              @changeoption="changeModelBefore"
              placeholder="请输入车型代码"
            ></car-model-select>
          </a-form-model-item>
        </a-col>
        <!-- 智驾域版本号 -->
        <a-col :md="6" :sm="24">
          <a-form-model-item prop="versionName">
            <span slot="label">
              {{ $t('smartDrivingDomainVersion') }}
              <question-mark-tip
                :tip-title="$t('inputVersionNameTipForTest')"
                :popupContainer="getPopupContainer"
              ></question-mark-tip>
            </span>
            <a-input v-model="formData.versionName" :disabled="true"/>
          </a-form-model-item>
        </a-col>
        <!-- 任务升级名称 -->
        <a-col :md="6" :sm="24">
          <a-form-model-item prop="name">
            <template #label>
              <span>{{ $t('campaignName') }}</span>
              <question-mark-tip
                :tip-title="'默认命名规则：测试类型_车型代码_智驾域测试版本号_日期时分秒'"
                :popupContainer="getPopupContainer">
              </question-mark-tip>
            </template>
            <a-input v-model="formData.name" />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="40">
        <!-- 升级类型 -->
        <a-col :md="6" :sm="24">
          <a-form-model-item prop="type">
            <template #label>
              <span>{{ $t('upgradeType') }}</span>
              <question-mark-tip
                :tip-title="$t(upgradeTriggerType === 'USER' ? 'testUserTaskUpgradeTypeTip' : 'testAutoTaskUpgradeTypeTip')"
                :popupContainer="getPopupContainer">
              </question-mark-tip>
            </template>
            <a-radio-group v-model="upgradeTriggerType" @change="()=>{
              formData.ecuUpdateType=1;formData.circleStrategyId=undefined;
              formData.silenceUpgrade=undefined;formData.forceUpgrade=undefined}">
              <a-radio :key="9" value="USER">{{$t('usersj')}}</a-radio>
              <a-radio :key="8" value="AUTO">{{$t('zdsj')}}</a-radio>
            </a-radio-group>
          </a-form-model-item>
        </a-col>
        <a-col :md="6" :sm="24">
          <!-- 强制升级 -->
          <a-form-model-item
            prop="forceUpgrade"
            key="forceUpgrade"
            v-if="upgradeTriggerType === 'USER'"
          >
            <template #label>
              <span>{{ $t('isQzsj') }}</span>
              <question-mark-tip :tip-title="$t('forceUpgradeTip')" :popupContainer="getPopupContainer">
              </question-mark-tip>
            </template>
            <a-radio-group v-model="formData.forceUpgrade" >
              <a-radio
                v-for="(item,index) in forceUpgradeType"
                :key="index"
                :value="item.value"
              >
                {{ $t(item.name) }}
              </a-radio>
            </a-radio-group>
          </a-form-model-item>
          <!-- 静默升级 -->
          <a-form-model-item
            key="silenceUpgrade"
            v-else
            prop="silenceUpgrade"
          >
            <template #label>
              <span>{{ $t('sfjmsj') }}</span>
              <question-mark-tip :tip-title="$t('silenceUpgradeTip')" :popupContainer="getPopupContainer">
              </question-mark-tip>
            </template>
            <a-radio-group v-model="formData.silenceUpgrade" >
              <a-radio
                v-for="(item,index) in slienceUpgradeType"
                :key="index"
                :value="item.value"
              >
                {{ $t(item.name) }}
              </a-radio>
            </a-radio-group>
          </a-form-model-item>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-row>
            <a-col :md="18" :sm="24">
              <!-- ECU升级类型 -->
              <a-form-model-item
                prop="ecuUpdateType"
                v-if="testType === 'develop'"
              >
                <template #label>
                  <span>{{ $t('ECU升级类型') }}</span>
                  <question-mark-tip :tip-title="'请根据实际测试需求选择升级类型！注意：自由烧写不校验软件升级的适配性，容易误刷软件，请谨慎使用。'"
                  :popupContainer="getPopupContainer">
                  </question-mark-tip>
                </template>
                <a-radio-group v-model="formData.ecuUpdateType" @change="changeEcuUpdateType" :disabled="disabled">
                  <a-radio key="1" :value="1">{{ $t('cgsj') }}</a-radio>
                  <a-radio key="2" :value="2">{{ $t('平刷升级') }}</a-radio>
                  <a-radio key="3" :value="3" v-if="upgradeTriggerType === 'USER'">{{ $t('自由烧写') }}</a-radio>
                  <a-radio key="4" :value="4" v-if="upgradeTriggerType === 'USER'">{{ $t('循环升级') }}</a-radio>
                </a-radio-group>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <!-- 循环升级策略 -->
              <a-form-model-item prop="circleStrategyId" key="circleStrategyId1" v-if="formData.ecuUpdateType === 4">
                <template #label>
                  {{ $t('circularUpgradeStrategy') }}
                  <question-mark-tip
                    :tip-title="$t('circularUpgradeStrategyTip')"
                    :popupContainer="getPopupContainer"
                  ></question-mark-tip>
                </template>
                <strategy-select
                  :time="nowTime"
                  :query="stratetySelectQuery"
                  :version-type="testType"
                  :upgrade-trigger-type="upgradeTriggerType"
                  :default-strate-id="formData.circleStrategyId"
                  @changeoption="selectCircleStrategy"
                ></strategy-select>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-col>
      </a-row>
    </fieldset>
    <fieldset style="margin-top:10px">
      <legend>条件策略</legend>
      <TestStrategy :time="nowTime" :id="conditionStrategyId" ref="strategyRef"></TestStrategy>
    </fieldset>
    <fieldset style="margin-top:10px">
      <legend>智驾域版本配置</legend>
      <span class="ECUTitle">ECU配置信息</span>
      <span style="float:right;" v-if="formData.ecuUpdateType==1">
        诊断设置选项
        <a-radio-group v-model="formData.diagnoseFilter">
          <a-radio key="1" :value="1">{{$t('只诊断任务配置ECU')}}</a-radio>
          <a-radio key="0" :value="0">{{$t('诊断所有智驾ECU')}}</a-radio>
        </a-radio-group>
      </span>
      <ecu-version-config
        :model-id="formData.modelId"
        :time="nowTime"
        :versionType="versionType"
        :default-versions="defaultSelectedVersions"
        ref="ecuVersionConfigRef"
      ></ecu-version-config>
    </fieldset>
    <!-- 发布说明 -->
    <fieldset style="margin-top:10px">
      <legend>{{$t('releaseNote')}}</legend>
      <div>
        <a-row>
          <a-col :md="24" :sm="24">
            <!-- 功能新增 -->
            <a-form-model-item :label="$t('funcAdd')" prop="functionAddition">
              <custom-text-area
                @change="handlerChange('functionAddition', $event)"
                :val="formData.functionAddition"
                :max-len="500"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :md="24" :sm="24">
            <!-- 功能优化 -->
            <a-form-model-item :label="$t('funcOptimize')" prop="functionOptimization">
              <custom-text-area
                @change="handlerChange('functionOptimization', $event)"
                :val="formData.functionOptimization"
                :max-len="500"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
      </div>
      <a-row>
        <a-col :md="24" :sm="24">
          <!-- 特别鸣谢 -->
          <a-form-model-item :label="$t('specialThanks')" prop="acknowledgements">
            <custom-text-area
              @change="handlerChange('acknowledgements', $event)"
              :val="formData.acknowledgements"
              :max-len="45"
            ></custom-text-area>
          </a-form-model-item>
        </a-col>
      </a-row>
      <!-- 版本声明 -->
      <div>
        <b>版本声明（仅Di6平台需填写）</b>
        <a-table
          :columns="explainsColumns"
          :data-source="formData.functionDi6Info.functionDi6Infos"
          :rowKey="(record, index) => {return index}"
          :pagination="false"
          :scroll="{ y:270 }"
          style="margin-top:10px;"
        >
          <template slot="functionTitle" slot-scope="text,record,index">
            <!-- <a-form-model-item
            :prop="'changeExplains.'+index+'.changeBefore'"
            :rules="rules.changeBefore">
              <a-input v-model="record.changeBefore" :max-length="1000"></a-input>
            </a-form-model-item> -->
            <a-form-model-item
                :key="'functionDi6Info-title'+index"
                :prop="'functionDi6Info.functionDi6Infos.' + index + '.functionTitle'"
                :rules="{message: '功能描述标题不能为空', trigger: 'change',max:23}"
              >
                <a-input :maxLength="23"
                  v-model="record.functionTitle"
                  placeholder="输入功能描述标题......"
                  style="width: 90%; margin-right: 8px"
                />
              </a-form-model-item>
          </template>
          <!-- 功能描述 -->
          <template slot="functionMsg" slot-scope="text,record,index">
            <!-- <a-form-model-item
            :prop="'changeExplains.'+index+'.inflectContent'"
            :rules="rules.inflectContent">
              <a-input  v-model="record.inflectContent" :max-length="1000"></a-input>
            </a-form-model-item> -->
            <a-form-model-item
              :name="['functionDi6Infos', index, 'desc']"
              :key="'functionDi6Info-msg'+index"
              :prop="'functionDi6Info.functionDi6Infos.' + index + '.functionMsg'"
              :rules="{message: '功能描述不能为空', trigger: 'change',}"
            >
              <a-input :maxLength="500"
                placeholder="输入功能描述......"
                v-model="record.functionMsg"
                style="width: 100%; margin-right: 8px"
              />
            </a-form-model-item>
          </template>
          <!-- 操作 -->
          <template slot="operation" slot-scope="text,record,index">
            <a-button @click="removeFunctionDi6Info(index)" v-if="formData.functionDi6Info.functionDi6Infos.length>1">
              {{$t('delete')}}
            </a-button>
          </template>
        </a-table>
        <div>
          <a-button style="margin-right:10px; border:1px solid #147092;color:#147092" @click="addFunctionDi6Info">
            <a-icon type="plus-circle" theme="filled" />{{$t('plus')}}
          </a-button>
        </div>
      </div>
    </fieldset>
    <!-- 升级预约时间 -->
    <fieldset style="margin-top:10px" v-if="upgradeTriggerType === 'AUTO'">
      <legend>升级预约时间</legend>
      <a-form-model-item prop="">
        <div class="editTestFormBoxTableList" id="mustshowoption">
          <a-table rowKey="id" :scroll="{y:350}" :dataSource="appointTimeDataSource" :columns="appointTimeColumns" :pagination="false" :table-layout="'fixed'">
            <template slot="appointTime" slot-scope="text,record">
              <a-range-picker v-if="currentRecord.id==record.id"
                              :placeholder="[$t('startTime'), $t('endTime')]"
                              :showTime="{ format: 'HH:mm:ss' }"
                              format="YYYY-MM-DD HH:mm:ss"
                              @change="onTimeRangeChange"
                              :value="defaultTimeRange"
                              :disabled-date="disabledDate"
                              :disabledTime="disabledEndTime"
                              :allow-clear="false"
                              style="max-width:100%;"
                              @ok="handleConfirm(record.id)"
                              :getCalendarContainer="getCalendarContainer"
              />
              <template v-else>
                {{record.startTime}} ~ {{record.endTime}}
              </template>
            </template>
            <template slot="operation" slot-scope="text,scope,index">
              <!-- <el-button type="text" v-if="currentRecord.id==scope.id" @click="handleConfirm(scope.id)">{{$t('确定')}}</el-button> -->
              <el-button type="text" @click="handleEdit(scope.id)">{{$t('edit')}}</el-button>
              <el-button type="text" v-if="appointTimeDataSource.length!=1 && upgradeTriggerType === 'AUTO'" @click="handleDelete(scope)">{{$t('delete')}}</el-button>
              <el-button type="text" v-if="index == (appointTimeDataSource.length-1) && upgradeTriggerType === 'AUTO'" @click="handleAdd(scope)">{{$t('add')}}</el-button>
            </template>
          </a-table>
        </div>
      </a-form-model-item>
    </fieldset>
    <!-- 升级车辆 -->
    <fieldset style="margin-top:10px">
      <legend>升级车辆</legend>
      <!-- 测试车辆标题 -->
      <div class="editTestFormBoxTableTitle">
        <!-- 测试车辆搜索区域 -->
        <a-row :gutter="[16,0]">
          <a-col
            :xs="24"
            :sm="12"
            :md="8"
            :lg="8"
            :xl="8"
            :xxl="8">
            <a-input @keyup.enter="handleSearch" :placeholder="$t('pleaseInput') + 'VIN'" v-model="testVehicleQuery.vin" />
          </a-col>
          <a-col
            :xs="24"
            :sm="24"
            :md="24"
            :lg="8"
            :xl="8"
            :xxl="8"
            class="btnWarp">
            <a-button type="info" @click="handleSearch" style="margin-right:8px;">
              <i class="iconfont icon-chazhao"></i>
              {{ $t('inquiry') }}
            </a-button>
            <a-button @click="clearCondition">
              <i class="iconfont icon-qingkong"></i>
              {{ $t('clear') }}
            </a-button>
          </a-col>
        </a-row>
      </div>
      <!-- 测试车辆列表 -->
      <div>
        <s-table
          ref="table"
          row-key="id"
          :columns="columns"
          :data="getVehicleTbData"
          :scroll="{x:2000,y:1000}"
          :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange,getCheckboxProps:onGetCheckboxProps}"
          class="h100"
        >
          <template slot="vin" slot-scope="text">
            <table-ellipsis :text="text || '-'"></table-ellipsis>
          </template>
          <template slot="usage" slot-scope="text,record">
            <table-ellipsis v-if="!text && record.status===1" :text="$t('available')"></table-ellipsis>
            <span v-if="record.status===0">不可用</span>
            <a v-if="!!text && record.status===1" @click="showUsingTask(record)">{{ $t('inUse') }}</a>
          </template>
          <template slot="model" slot-scope="text">
            <table-ellipsis :text="text || '-'"></table-ellipsis>
          </template>
          <template slot="stereotype" slot-scope="text">
            <table-ellipsis :text="text || '-'"></table-ellipsis>
          </template>
          <template slot="brandName" slot-scope="text">
            <table-ellipsis :text="text || '-'"></table-ellipsis>
          </template>
          <template slot="province" slot-scope="text">
            <table-ellipsis :text="$t(text) || '-'"></table-ellipsis>
          </template>
          <template slot="timeOfCreation" slot-scope="text">
            <table-ellipsis :text="$commonFun.getDateTimeStr(text) || '-'"></table-ellipsis>
          </template>
        </s-table>
      </div>
    </fieldset>


    <!-- 查看使用中的车辆当前任务列表弹框 -->
    <tasks-in-vehicle-dialog
      @releaseok="refreshData"
      ref="tasksInVehicleDialog"
      v-if="tasksInVehicleQuery"
      :query="tasksInVehicleQuery"></tasks-in-vehicle-dialog>
    <!-- 查看策略 -->
    <show-condition-update-strategy
      ref="showStrategy"
      :updataStrategyId="formData.strategyId"
    ></show-condition-update-strategy>
    <StrategyTableSelector ref="strategyTableSelector"
                           :version-type="'TEST'"
                           :test-type="testType"
                           v-if="upgradeTriggerType"
                           :upgrade-trigger-type="upgradeTriggerType"
                           @ok="(id) => changeStrategy(id)"/>
  </a-form-model>
</template>
<script>
import tableEllipsis from '@/components/Ellipsis/TableEllipsis'
import lodash from 'lodash'
import { strategyTestVehicleColumns,explainsColumns } from '../config/list'
import { strategyTestInitFormData } from '../config/form'
import { STable } from '@/components'
import { checkTextLen,checkVersionName } from '@/utils/validate'
import QuestionMarkTip from '@/views/components/QuestionMarkTip'
import StrategySelect from '@/views/components/StrategySelect'
import moment from 'moment'
import taskApi from '@/api/modules/task'
import TasksInVehicleDialog from '@/views/components/TasksInVehicle/dialog.vue'
import FactoryChannelSelect from '@/views/components/FactoryChannelSelect.vue'
import ShowConditionUpdateStrategy from '@/views/components/ShowConditionUpdateStrategy'
import StrategyTableSelector from '@/views/task/components/StrategyTableSelector.vue'
import { strategyPerms } from '@/config/permission/index'
import AuthButton from '@/components/AuthButton'
import TestStrategy from '@/views/strategy/FotaUpdate/components/TestStrategy.vue'
import CarModelSelect from '@/views/components/CarModelSelect'
import EcuVersionConfig from '@/views/software/vehicleVersion/components/EcuVersionConfig.vue'
import CustomTextArea from '@/components/CustomTextArea/index.vue'

export default {
  components: {
    tableEllipsis,
    STable,
    QuestionMarkTip,
    StrategySelect,
    TasksInVehicleDialog,
    ShowConditionUpdateStrategy,
    StrategyTableSelector,
    AuthButton,
    FactoryChannelSelect,
    TestStrategy,
    CarModelSelect,
    EcuVersionConfig,
    CustomTextArea },
  props: {
    copyId: {
      type: String,
      default: ''
    },
    testType: {
      type: String,
      default: ''
    },
    editRecord: {
      type: Object,
      default: () => {
        return {}
      }
    },
    time: {
      type: Number,
      default: 123
    },
    fromGcy:{
      type: Boolean,
      default: true
    }
  },
  computed: {
    showStable () {
      return this.formData.strategyId
    },
    // 有效期选择的默认值
    defaultTimeRange () {
      if (this.formData.startTime && this.formData.endTime) {
        return [moment(this.formData.startTime), moment(this.formData.endTime)]
      }
      return []
    },
    testTaskType () {
      return this.$store.state.task.testTaskType
    },
    forceUpgradeType () {
      return this.$store.state.task.forceUpgradeType
    },
    slienceUpgradeType () {
      return this.$store.state.task.slienceUpgradeType
    }
  },
  data () {
    return {
      // 条件策略id
      conditionStrategyId:'',
      // 车型代码 用于拼接升级任务名称
      code:'',
      explainsColumns,
      // 默认已选中的零件配置
      defaultSelectedVersions: null,
      versionType:'TEST',
      nowTime: Date.now(),
      upgradeTriggerType: 'USER',
      strategyName: '',
      strategyPerms,
      firstTime:moment(new Date().getTime()).format('YYYY-MM-DD HH:mm:ss'),
      formData: lodash.cloneDeep(strategyTestInitFormData),
      rules: {
        modelId: [{ required: true, message: this.$t('pleaseSelect') }],
        name: [
          { required: true, message: this.$t('pleaseInput') },
          { validator: checkTextLen() }
        ],
        code:[
          { required: true, pattern: /^[1-9][0-9]{0,16}$/, message: this.$t('digits17') }
        ],
        type: [
          { required: true, message: this.$t('pleaseInput') }
        ],
        circleStrategyId: [
          { required: true, message: this.$t('pleaseInput') }
        ],
        startTime: [
          { required: true, message: this.$t('pleaseInput') }
        ],
        strategyId: [{ required: true, message: this.$t('pleaseSelect') }],
        isCircleUpgrade: [{ required: true, message: this.$t('pleaseSelect') }],
        forceUpgrade: [{ required: true, message: this.$t('pleaseSelect') }],
        silenceUpgrade: [{ required: true, message: this.$t('pleaseSelect') }],
        factoryChannel: [{ required: true, message: this.$t('pleaseSelect') }],
        freeBurning: [{ required: true, message: this.$t('pleaseSelect') }],
        description: [{ required: true, message: this.$t('pleaseInput') }, { validator: checkTextLen(500, true) }],
        functionAddition: [{ required: true, message: this.$t('pleaseInput') }, { validator: checkTextLen(500, true) }],
        functionOptimization: [
          { required: true, message: this.$t('pleaseInput') },
          { validator: checkTextLen(500, true) }
        ],
        acknowledgements: [{ validator: checkTextLen(45) }],
        ecuUpdateType: [{ required: true, message: this.$t('pleaseSelect') }],
      },
      data: [{ id: 1 }, { id: 2 }],
      columns: strategyTestVehicleColumns,
      // 已选中的表格行keys
      selectedRowKeys: [],
      stratetySelectQuery: null,
      // 测试车辆搜索条件
      testVehicleQuery: {
        vin: '',
        vehicleType: 2,
        modelIds:[]
      },
      tasksInVehicleQuery: null,
      currentRecord:{},
      appointTimeColumns:[
        {
          title: '预约时间段',
          dataIndex: 'serialNo',
          width:80,
          key: 'serialNo',
          customRender:(text,record,index)=>`${index+1}`
        },
        {
          title: '预约升级时间',
          dataIndex: 'appointTime',
          key: 'appointTime',
          scopedSlots: { customRender: 'appointTime' },
          width:300
        },
        {
          title: '操作',
          dataIndex: 'operation',
          key: 'operation',
          scopedSlots: { customRender: 'operation' },
          width:100
        },
      ],
      //默认一行数据
      appointTimeDataSource:[
        {
          id:new Date().getTime(),
          startTime:moment(new Date().getTime()).format('YYYY-MM-DD HH:mm:ss'),
          endTime:moment(new Date().getTime()).add(this.upgradeTriggerType === 'USER' ? 43200 : 30, 'minutes').format('YYYY-MM-DD HH:mm:ss')
        }
      ],
      disabled: false
    }
  },
  watch: {
    'formData.modelId':{
      handler(val){
        this.stratetySelectQuery = {
          type: 1,
          modelId: val,
          excludeVehicleVersionId: '-1'
        }
        this.formData.circleStrategyId=undefined
        this.nowTime=Date.now()
      }
    },
    'formData.versionName':{
      handler(val){
        if(val && this.copyId){
          this.formData.name=`${this.testType}_${this.code}_${this.formData.versionName}`
        }else if(val){
          this.formData.name=`${this.testType}_${this.code}_${this.formData.versionName}`
        }
      }
    },
    time: {
      handler(val) {
        // this.resetFormData()
        this.nowTime = val
      },
    },
    editRecord: {
      handler (val) {
        if (!val) {
          return
        }
        const oldStrategyId = this.formData.strategyId
        this.selectedRowKeys = []
        // this.formData.name = val.name
        this.formData.strategyId = val.strategyId
        this.changeStrategy(val.strategyId);
        this.formData.circleStrategyId = undefined
        this.formData.startTime = ''
        this.formData.endTime = ''
        console.log(this.formData, 'formData')
        this.stratetySelectQuery = {
          type: 1,
          modelId: val.modelId,
          excludeVehicleVersionId: val.vehicleVersionId
        }
        if (oldStrategyId) {
          this.$nextTick(() => {
            this.refreshData()
          })
        }
      },
      immediate: true
    },
    // 'formData.freeBurning' (val, old) {
    //   if (val === 1) {
    //     this.disabled = true
    //     this.formData.isEqualUpgrade = false
    //     this.formData.isCircleUpgrade = false
    //   } else if (val === 0) {
    //     this.disabled = false
    //   }
    // }
  },
  created(){
    this.$set(this.formData, 'code', moment(new Date().getTime()).format('YYYYMMDDHHmmss'))
    // 进入页面，自动生成测试域版本号
    this.initTestVehicleVersion()
    if(this.copyId){
      this.init()
    }
  },
  methods: {
    init(){
      this.$api.getDevelopTaskInfor({id:this.copyId}).then(res=>{
        const data = res.data
        if(data){
          this.nowTime=Date.now()
          // 任务配置
          this.formData.modelId = data.modelId
          this.refreshData()
          this.code=data.vehicleVersionResponse.model.code

          this.upgradeTriggerType = data.type == 8? 'AUTO':'USER'
          this.formData.forceUpgrade = data.forceUpgrade
          this.formData.silenceUpgrade = data.silenceUpgrade
          this.formData.ecuUpdateType = data.freeBurning?3:data.isEqualUpgrade?2:data.circleStrategyId?4:1
          this.formData.diagnoseFilter = data.diagnoseFilter?data.diagnoseFilter:0
          this.conditionStrategyId=data.conditionStrategyId
          this.formData.circleStrategyId=data.circleStrategyId
          // 发布说明
          this.formData.functionAddition = data.vehicleVersionResponse.functionAddition
          this.formData.functionOptimization = data.vehicleVersionResponse.functionOptimization
          this.formData.acknowledgements = data.vehicleVersionResponse.acknowledgements
          this.formData.functionDi6Info =
          data.vehicleVersionDi6Response || lodash.cloneDeep(strategyTestInitFormData.functionDi6Info)
          if (
            !this.formData.functionDi6Info.functionDi6Infos ||
            this.formData.functionDi6Info.functionDi6Infos.length === 0
          ) {
            this.formData.functionDi6Info.functionDi6Infos = [
              ...strategyTestInitFormData.functionDi6Info.functionDi6Infos
            ]
          }
          // 智驾域版本配置
          const ecuVersions = {}
          data.vehicleVersionResponse.ecuVersions.forEach(version => {
            ecuVersions[version.ecuId] = {
              versionId: version.versionId,
              versionName: version.version.name,
              versionType: version.version.versionType,
              groupRollback: version.groupRollback,
              groupNo: version.groupNo,
              groupUpgradeNo: version.groupUpgradeNo,
              releaseNotes: version.releaseNotes || []
            }
          })
          this.defaultSelectedVersions = ecuVersions

          // ECU升级类型判断
          if(data.isEqualUpgrade){
            this.formData.freeBurning=0
            this.formData.isEqualUpgrade=true
            this.formData.isCircleUpgrade=false
          }else if(data.freeBurning){
            this.formData.freeBurning=1
            this.formData.isEqualUpgrade=false
            this.formData.isCircleUpgrade=false
          }else if(data.circleStrategyId){
            this.formData.isCircleUpgrade=true
            this.formData.isEqualUpgrade=false
            this.formData.freeBurning=0
          }else{
            this.formData.freeBurning=0
            this.formData.isEqualUpgrade=false
            this.formData.isCircleUpgrade=false
          }
        }
      })
    },
    changeEcuUpdateType(e){
      if(e.target.value==1){
        this.formData.isEqualUpgrade=false
        this.formData.freeBurning=0
        this.formData.isCircleUpgrade=false
      }else if(e.target.value==2){
        this.formData.isEqualUpgrade=true
        this.formData.freeBurning=0
        this.formData.isCircleUpgrade=false
      }else if(e.target.value==3){
        this.formData.freeBurning=1
        this.formData.isEqualUpgrade=false
        this.formData.isCircleUpgrade=false
      }else if(e.target.value==4){
        this.formData.isCircleUpgrade=true
        this.formData.isEqualUpgrade=false
        this.formData.freeBurning=0
      }
    },
    // 添加版本说明
    addFunctionDi6Info() {
      if (this.formData.functionDi6Info.functionDi6Infos.length > 20) {
        this.$message.warn('功能描述不能超过20项！')
      }
      this.formData.functionDi6Info.functionDi6Infos.push({
        functionMsg: '',
        functionTitle: ''
      })
    },
    removeFunctionDi6Info(index) {
      // let index = this.formData.functionDi6Info.functionDi6Infos.indexOf(item)
      if (index !== -1) {
        this.formData.functionDi6Info.functionDi6Infos.splice(index, 1)
      }
    },
    handlerChange(key, val) {
      this.formData[key] = val
    },
    changeModelBefore(val,item) {
      const _this = this
      const configData = this.$refs.ecuVersionConfigRef.getConfigData()
      if (configData.length === 0) {
        this.changeModel(val,item)
        return
      }
      this.$confirm({
        title: _this.$t('systemTip'),
        content: '更换车型后【智驾域版本配置】里面ECU清单会同步更换，确定切换？',
        onOk() {
          _this.changeModel(val,item)
          _this.defaultSelectedVersions = null
        },
        onCancel() {}
      })
    },
    changeModel(val,item) {
      this.formData.modelId = val
      if(item){
        this.code=item.code
        this.formData.name=`${this.testType}_${item.code}_${this.formData.versionName}`
      }
      this.$nextTick(() => {
        this.$refs.formComp.validateField('modelId')
        this.$refs.formComp.validateField('name')
      })
      this.testVehicleQuery.modelIds=[val]
      this.refreshData()
      this.nowTime = Date.now()
    },
    // 查看当前车辆正在执行的任务列表
    showUsingTask (record) {
      console.log(record, 'record')
      this.tasksInVehicleQuery = {
        vehicleId: record.id
      }
      this.$nextTick(() => {
        this.$refs.tasksInVehicleDialog.toggleVisible(true)
      })
    },
    // 修改唤醒通道
    changeoption ($event, key) {
      this.$set(this.formData, key, $event)
      this.$refs.formComp.validateField(key)
    },
    handleSearch () {
      this.refreshData()
    },
    clearCondition () {
      this.selectedRowKeys=[]
      this.testVehicleQuery.vin = ''
      this.refreshData()
    },
    getPopupContainer () {
      return document.body
    },
    getCalendarContainer () {
      return document.querySelector('#mustshowoption') || document.body
    },
    onGetCheckboxProps: record => ({
      // taskOccupied任务占用中不可使用
      props: {
        disabled: record.taskOccupied || record.status === 0
      }
    }),
    onSelectChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    // 获取车辆数据
    getVehicleTbData (parameter) {
      console.log('abc', 22442, this.formData, this.editRecord.modelId)
      const query = {
        ...parameter,
        // modelIds:[this.formData.modelId],
        // modelIds: [this.editRecord.modelId],
        ...this.testVehicleQuery
      }
      if(this.formData.modelId){
        this.testVehicleQuery.modelIds=[this.formData.modelId]
        query.modelIds=[this.formData.modelId]
      }else{
        return
      }
      return this.$store.dispatch('getVehiclePageData', query)
    },
    selectCircleStrategy (val) {
      this.formData.circleStrategyId = val
      this.$refs.formComp.validateField('circleStrategyId')
    },
    getFormData () {
      const thisWeb = this

      return new Promise((resolve, reject) => {
        this.$refs.formComp.validate(valid => {
          if(!this.$refs.strategyRef.toQualityFormData().items.length){
            reject()
            return
          }
          let configData = this.$refs.ecuVersionConfigRef.getConfigData()
          if (!this.otherCheckConfigData(configData)) {
            reject(new Error(this.$t('pleaseInput') + this.$t('ecuVersion')).toLowerCase())
            return
          }

          if (!valid) {
            reject(valid)
            return
          }
          if (!this.otherCheck()) {
            reject(new Error('未选择车辆'))
            return
          }
          if(this.handleConfirm()==false){
            return
          }
          this.selectedVehicleOccupied().then((result) => {
            if (result) {
              const data = lodash.clone(this.formData)
              if (this.id && !this.$refs.ecuVersionConfigRef.checkConfigIsDiff(configData)) {
                // 是编辑的时候且零件配置信息没有变化的时候后端要求传递[]
                configData = []
              }

              //liangminglong
              //data.startTime = data.startTime + ':00'
              //data.endTime = data.endTime + ':00'
              data.vehicleIds = [...this.selectedRowKeys]
              delete data.circleStrategyId

              //循环升级与平刷升级互斥
              // if(data.isEqualUpgrade === true){
              //   data.isCircleUpgrade = false;
              // }

              if (this.upgradeTriggerType === 'USER' ) {
                if (data.ecuUpdateType === 4) {
                  //用户循环
                  data.type = 10;
                  data.circleStrategyId = this.formData.circleStrategyId
                } else {
                  //用户非循环
                  data.type = 9;
                }
              } else if (this.upgradeTriggerType === 'AUTO'){
                //自动升级
                data.type = 8;
              }
              //预约升级时间
              if(this.upgradeTriggerType === 'AUTO'){
                data.taskAppointTimeDto = this.appointTimeDataSource;
              }else{
                data.taskAppointTimeDto = [
                  {
                    id:new Date().getTime(),
                    startTime:moment(new Date().getTime()).format('YYYY-MM-DD HH:mm:ss'),
                    endTime:moment(new Date().getTime()).add(100, 'years').format('YYYY-MM-DD HH:mm:ss')
                  }
                ]
              }
              data.factoryChannel='1'
              // 条件策略
              data.strategyId=0
              data.taskName=this.formData.name
              data.items=this.$refs.strategyRef.toQualityFormData().items
              data.vehicleVersionAddRequestDto=lodash.clone(this.formData)
              data.vehicleVersionAddRequestDto.fromGcy=this.fromGcy
              data.vehicleVersionAddRequestDto.ecuVersions = configData
              data.vehicleVersionAddRequestDto.name=data.versionName
              if (data.freeBurning === 1) {
                const vm = this;
                this.$confirm({
                  title: this.$t('systemTip'),
                  content: '自由烧写任务不校验ECU软件的适配性，确认是否创建自由烧写任务?',
                  onOk() {
                    resolve(data);
                  },
                  onCancel() {
                  }
                });
              } else {
                thisWeb.$api.getNextVehicleVersion().then(res=>{
                  if(res.code == 0){
                    console.info(res.data)
                    const old = thisWeb.formData.versionName
                    // 因为测试智驾域版本号是自动生成的，在提交前进行再次获取最新
                    thisWeb.formData.versionName = res.data
                    const newOne = thisWeb.formData.versionName

                    if(old != newOne){
                      this.openNotification(old, newOne)
                      return
                    }
                    resolve(data);
                  }else{
                    reject(new Error('无法查询最新可用版本号'))
                    return
                  }
                })
              }
            }
          })
        })
      })
    },
    otherCheckConfigData(configData) {
      if (configData.length === 0) {
        const msg = this.$t('pleaseSelect') + this.$t('ecuVersion').toLowerCase()
        this.$message.error(msg)
        return false
      }
      return true
    },
    otherCheck () {
      if (this.selectedRowKeys.length === 0) {
        this.$message.error(this.$t('pleaseSelect') + this.$t('test').toLowerCase() + this.$t('vehicle').toLowerCase())
        return false
      }
      return true
    },
    selectedVehicleOccupied () {
      return new Promise((resolve) => {
        taskApi.checkTaskVehicleOccupied({ ids: this.selectedRowKeys }).then((res) => {
          if (res.data.length === 0) {
            resolve(true)
          } else {
            // 选择的已被禁止，需要提示，并修改表格中的数据
            if (res.data.length === this.selectedRowKeys.length) {
              this.$message.error(this.$t('testTaskSelectVehicleTip1'))
              this.selectedRowKeys = []
            } else {
              this.$message.error(this.$t('testTaskSelectVehicleTip2').replace('__CONTENT__', res.data.length))
              this.selectedRowKeys = this.selectedRowKeys.filter(key => !res.data.includes(key))
            }
            this.refreshData()
            resolve(false)
          }
        })
      })
    },
    resetFormData () {
      // this.formData.name = `${this.$t('test')}${this.$t('strategy')}[${this.$commonFun.getDateMinuteStr(new Date())}]`
      this.selectedRowKeys = []
      this.defaultSelectedVersions = null
    },
    refreshData (isToFirstPage = true) {
      if (!this.$refs.table) {
        return
      }
      let obj = null
      if (isToFirstPage) {
        obj = { current: 1 }
      }
      this.$refs.table.loadData(obj)
    },
    // 调用后台接口，生成最新的测试域版本号
    initTestVehicleVersion(){
      this.$api.getNextVehicleVersion().then(res=>{
        if(res.code == 0){
          this.formData.versionName = res.data;
        }
      })
    },
    // eslint-disable-next-line consistent-return
    onTimeRangeChange (date, dateString) {
      if (date.length === 0) {
        this.formData.startTime = ''
        this.formData.endTime = ''
        return false
      }
      const minDays = 1
      //if (moment(date[1]).diff(moment(date[0]), 'days') < minDays) {
      //  this.$message.error(this.$t('newTaskTimeTip2'))
        // eslint-disable-next-line prefer-destructuring
        //this.formData.startTime = dateString[0]
        //this.formData.endTime = moment(dateString[0]).add(minDays, 'days').format('YYYY-MM-DD HH:mm:ss')
      //  return false
      //}
      // eslint-disable-next-line prefer-destructuring
      this.formData.startTime = dateString[0]
      // eslint-disable-next-line prefer-destructuring
      this.formData.endTime = dateString[1]
      //更新日期到时间数组中
      this.appointTimeDataSource.forEach(data=>{
        if (data.id == this.currentRecord.id){
          data.startTime= dateString[0]
          data.endTime= dateString[1]
        }

      })
    },
    range(start, end){
      const result = [];
      for (let i = start; i < end; i++) {
          result.push(i);
      }
      return result;
    },
    disabledEndTime(date,type){
      let currentDay = moment().date();    //当下的时间
      let currentHours = moment().hours();
      let currentMinutes = moment().minutes(); 
      if(type=='start' && date){
        let settingHours = moment(date[0]).hours();
        let settingDay = moment(date[0]).date();
        if (date[0] && settingDay === currentDay && settingHours === currentHours) {
          return {       
            disabledHours: () => this.range(0, currentHours),         //设置为当天现在这小时，禁用该小时，该分钟之前的时间
            disabledMinutes: () => this.range(0, currentMinutes),
          };
        }else if (date[0] && settingDay === currentDay && settingHours > currentHours) {
            return { 
                disabledHours: () => this.range(0, currentHours),      //设置为当天现在这小时之后，只禁用当天该小时之前的时间 
                disabledMinutes: () => [],
            };   
        }else if (date[0] && settingDay === currentDay && settingHours < currentHours) {
            return {
                disabledHours: () => this.range(0, currentHours),      //若先设置了的小时小于当前的，再设置日期为当天，需要禁用当天现在这小时之前的时间和所有的分
                disabledMinutes: () => this.range(0, 59),
            }
        }else if (date[0] && settingDay > currentDay) {
            return {                                    
                disabledHours: () => [],                     //设置为当天之后的日期，则不应有任何时间分钟的限制
                disabledMinutes: () => [],
            }
        }
      }else if(type=='end' && date){ 
        let settingHours = moment(date[1]).hours();
        let settingDay = moment(date[1]).date();
        if (date[1] && settingDay === currentDay && settingHours === currentHours) {
          return {       
            disabledHours: () => this.range(0, currentHours),         //设置为当天现在这小时，禁用该小时，该分钟之前的时间
            disabledMinutes: () => this.range(0, currentMinutes),
          };
        }else if (date[1] && settingDay === currentDay && settingHours > currentHours) {
            return { 
                disabledHours: () => this.range(0, currentHours),      //设置为当天现在这小时之后，只禁用当天该小时之前的时间
                disabledMinutes: () => [],
            };   
        }else if (date[1] && settingDay === currentDay && settingHours < currentHours) {
            return {
                disabledHours: () => this.range(0, currentHours),      //若先设置了的小时小于当前的，再设置日期为当天，需要禁用当天现在这小时之前的时间和所有的分
                disabledMinutes: () => this.range(0, 59),
            }
        }else if (date[1] && settingDay > currentDay) {
            return {                                    
                disabledHours: () => [],                     //设置为当天之后的日期，则不应有任何时间分钟的限制
                disabledMinutes: () => [],
            }
        }
      }
    },
    openNotification(old, newOne) {
      const key = `open${Date.now()}`;
      this.$notification.open({
        message: '提示',
        description:
          '智驾域版本号'+old+'已过期, 系统自动重新生成' + newOne,
        btn: h => {
          return h(
            'a-button',
            {
              props: {
                type: 'primary',
                size: 'small',
              },
              on: {
                click: () => this.$notification.close(key),
              },
            },
            '确认',
          );
        },
        key
      });
    },
    disabledDate (current) {
      return current < moment().subtract(1,"days").endOf('day')
    },
    handleEdit(id){
      this.currentRecord = this.appointTimeDataSource.filter(item => id === item.id)[0]
      this.formData.startTime = this.currentRecord.startTime
      this.formData.endTime = this.currentRecord.endTime
    },
    handleDelete(record){
      if (this.appointTimeDataSource.length === 1) {
        this.$message.error("默认要有一行数据！")
        return
      }
      this.appointTimeDataSource = this.appointTimeDataSource.filter(item => record.id !== item.id)
    },
    handleConfirm(id){
      //TODO 判断时间是否有重合
      const appointTimeDataSourceCopy=[...this.appointTimeDataSource]
      appointTimeDataSourceCopy.sort((a,b)=>{
        return new Date(a.startTime)-new Date(b.startTime)
      })
      for(let i=0;i<appointTimeDataSourceCopy.length;i++){
        if(i>0){
          if(moment(appointTimeDataSourceCopy[i].startTime).isBefore(moment(appointTimeDataSourceCopy[i-1].endTime))){
            this.$message.error("与现有时间段重合！")
            return false
          }
        }
        if(moment(appointTimeDataSourceCopy[i].startTime).isBefore(this.firstTime)){
          this.$message.error("时间不能早于当前时间")
          return false
        }
      }
      this.currentRecord ={}
    },
    handleAdd(scope){
      this.appointTimeDataSource.push(
        {
          id:new Date().getTime(),
          startTime:moment(scope.endTime).add(1, 'minutes').format('YYYY-MM-DD HH:mm:ss'),
          endTime:moment(scope.endTime).add(31, 'minutes').format('YYYY-MM-DD HH:mm:ss')
        }
      )

    },
    changeStrategy (val) {
      this.formData.strategyId = val
      this.strategyName = ''
      this.editRecord.modelId = ''
      if (val) {
        this.$store.dispatch('getStrategyDetailData', {id:val}).then((res) => {
          this.strategyName = res.data.name
          this.editRecord.modelId = res.data.modelId
        })
      }
    },
    // 查看策略
    showStrategy () {
      // lxhmodifyxccode
      if (!this.formData.strategyId) {
        this.$message.error(this.$t('firstPleaseSelectStrategy'))
        return
      }
      this.$refs.showStrategy.visible = true
    },


  },
}
</script>
<style scoped  lang="less">
.ECUTitle{
  //  margin-bottom: 10px;
    &::before {
      display: inline-block;
      content: '';
      width: 6px;
      background-color: rgba(67, 136, 166, 1);
      height: 14px;
      vertical-align: bottom;
      margin-right: 3px;
      margin-bottom: 4px;
    }
}
.editTestFormBox {
  display: flex;
  flex-direction: column;
  .editTestFormBoxTop {
    flex:none;
  }
  .editTestFormBoxTableTitle {
    flex:none;
    margin-bottom: 16px;
  }
  .editTestFormBoxTableList {
    flex:1 0 0;
    min-height: 130px;
  }
}
fieldset
{
  border: 1px solid #ccc;
  padding: 8px;
  legend{
    width:auto;
    border-bottom: none;
    color: blue;
    background-color: #FFFFFF;
    font-size: 14px;
    margin-bottom:0px
  }
}

</style>
